package com.ruoyi.uitity;

import java.net.URLEncoder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ExcelUtils {
    public static void exportXls(HttpServletResponse response, List<Map<String, Object>> dataList, String name, String[] headers, String[] engHeaders) throws IOException {
        // 使用 try-with-resources 自动管理资源
        try (Workbook wb = new XSSFWorkbook();
             OutputStream out = response.getOutputStream()) {

            Sheet sheet = wb.createSheet("Data");

            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 添加数据
            int rowNum = 1;
            int count = 1;
            for (Map<String, Object> data : dataList) {
                Row row = sheet.createRow(rowNum++);
                for (int i = 0; i < headers.length; i++) {
                    Cell cell = row.createCell(i);
                    if (i == 0) {
                        cell.setCellValue(count++);
                    } else {
                        Object value = data.get(engHeaders[i]);
                        cell.setCellValue(value == null ? "" : value.toString());
                    }
                }
            }

            // 设置响应头信息
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String formattedDate = dateFormat.format(new Date());
            String fileName = name + "_" + formattedDate + ".xlsx";

            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            // 写入文件
            wb.write(out);
        } catch (Exception e) {
            // 正确处理异常
            e.printStackTrace();
            throw new RuntimeException("导出Excel失败", e);
        }
    }
}
